/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.config;

import cn.star.framework.core.Constant;
import cn.star.framework.enhance.integrator.HibernateIntegrator;
import cn.star.framework.enhance.interceptor.CustomizeInterceptor;
import cn.star.framework.entity.AuditorAwareImpl;
import cn.star.framework.identity.UserIdentityService;
import cn.star.framework.strategy.IdStrategyAutoincrementValue;
import cn.star.framework.strategy.IdStrategySnowflakeValue;
import java.util.Collections;
import java.util.Properties;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.Interceptor;
import org.hibernate.id.enhanced.StandardOptimizerDescriptor;
import org.hibernate.id.enhanced.TableGenerator;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.spi.IntegratorProvider;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;

/**
 * 框架配置<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Configuration(value = "__F.AUTO_CONFIGURATION__")
@ConfigurationProperties(prefix = Constant.CONFIGURATION_PREFIX + ".framework")
public class AutoConfiguration {

  @Getter @Setter
  private IdStrategySnowflakeValueConfiguration snowflake =
      new IdStrategySnowflakeValueConfiguration();

  @Getter @Setter
  private IdStrategyAutoincrementValueConfiguration autoincrement =
      new IdStrategyAutoincrementValueConfiguration();

  /** {@link IdStrategySnowflakeValue} */
  public static class IdStrategySnowflakeValueConfiguration {
    /** 终端ID */
    @Getter @Setter private long workerId = 1;

    /** 数据中心ID */
    @Getter @Setter private long dataCenterId = 1;
  }

  /** {@link IdStrategyAutoincrementValue} */
  public static class IdStrategyAutoincrementValueConfiguration {
    /** 是否使用同一个序列生成所有表的主键值 */
    @Getter @Setter private boolean useSameSequence = false;

    /** 存储主键的表 */
    @Getter @Setter private String table = "autoincrement_sequence";

    /** 存储主键名称字段(主表名) */
    @Getter @Setter private String idColumn = "id_";

    /** 字段{@link #idColumn}长度 */
    @Getter @Setter private int idColumnLength = 255;

    /** 存储主键下一个值字段 */
    @Getter @Setter private String idValueColumn = "next_id_value_";

    /** 初始值 */
    @Getter @Setter private int initialValue = 1;

    /** 自增步长 */
    @Getter @Setter private int incrementSize = 1;

    /**
     * 在{@link IdStrategyAutoincrementValue#configure(Type, Properties, ServiceRegistry)}中需要注意Type的值
     * <br>
     * 使用{@link TableGenerator#makeValue()}<br>
     *
     * <pre>
     *   public static IntegralDataTypeHolder getIntegralDataTypeHolder(Class integralType) {
     *     if ( integralType == Long.class
     *         || integralType == Integer.class
     *         || integralType == Short.class ) {
     *       return new BasicHolder( integralType );
     *     }
     *     else if ( integralType == BigInteger.class ) {
     *       return new BigIntegerHolder();
     *     }
     *     else if ( integralType == BigDecimal.class ) {
     *       return new BigDecimalHolder();
     *     }
     *     else {
     *       throw new IdentifierGenerationException(
     *           "Unknown integral data type for ids : " + integralType.getName()
     *       );
     *     }
     *   }
     * </pre>
     *
     * 支持的值{@link StandardOptimizerDescriptor} <br>
     */
    @Getter @Setter private String optimizer = StandardOptimizerDescriptor.NONE.getExternalName();
  }

  // hibernate 框架内部Hibernate默认配置

  @Bean
  @ConditionalOnMissingBean(Interceptor.class)
  public Interceptor interceptor() {
    return new CustomizeInterceptor();
  }

  @Bean
  public HibernatePropertiesCustomizer customizer(Interceptor interceptor) {
    return (hibernateProperties) -> {
      hibernateProperties.put(
          EntityManagerFactoryBuilderImpl.INTEGRATOR_PROVIDER,
          (IntegratorProvider) () -> Collections.singletonList(HibernateIntegrator.INSTANCE));
      hibernateProperties.put("hibernate.ejb.interceptor", interceptor);
    };
  }

  // conditional ioc

  @Bean
  @ConditionalOnBean(UserIdentityService.class)
  public AuditorAware<String> auditorAware(UserIdentityService identityService) {
    return new AuditorAwareImpl(identityService);
  }
}
